package com.example.controller;

import com.google.code.kaptcha.Producer;
import jakarta.servlet.http.HttpSession;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class VerifyCodeController {
    @Autowired
    private Producer producer;
//    private final Producer producer;

//    @Autowired
//    public VerifyCodeController(Producer producer) {
//        this.producer = producer;
//    }

    @GetMapping(value = "/verifyCode.jpg")
    public String getKaptcha(HttpSession httpSession) throws IOException {
//        1、生成验证码，并将验证码写入到session中，可根据实际需要写入到redis中
        String codeText = producer.createText();
        httpSession.setAttribute("kaptcha", codeText);
        System.out.println("生成的验证码为："+codeText);
        BufferedImage bi = producer.createImage(codeText);

//        2、写入到内存中
//        ByteArrayOutputStream是字节数组输出流
        FastByteArrayOutputStream fbos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "png", fbos);
        
//        3、将验证码转为base64
        String base64Code = Base64.encodeBase64String(fbos.toByteArray());
        return base64Code;
    }
}
